from django.db import models
from django.utils.timezone import now

class Goods(models.Model):
    """商品模型"""
    goods_name = models.CharField(max_length=64, verbose_name="商品名称")
    goods_img = models.CharField(max_length=255, verbose_name="商品图片URL")
    goods_title = models.CharField(max_length=64, verbose_name="商品标题",null=True)
    goods_detail = models.CharField(max_length=64, verbose_name="商品详情", null=True)
    goods_price = models.DecimalField(max_digits=12, decimal_places=2, verbose_name="商品原价")
    goods_stock = models.IntegerField(verbose_name="商品库存")

    class Meta:
        db_table = 'goods'
        verbose_name = "商品"
        verbose_name_plural = "商品列表"

    def __str__(self):
        return self.goods_name


class SeckillGoods(models.Model):
    """秒杀商品模型"""
    # 主键字段
    id = models.BigAutoField(primary_key=True, verbose_name="秒杀商品ID")

    # 外键关联普通商品
    goods = models.ForeignKey(
        Goods,
        on_delete=models.CASCADE,
        related_name="seckill_goods",
        verbose_name="商品"
    )

    # 秒杀相关信息
    seckill_price = models.DecimalField(
        max_digits=12,
        decimal_places=2,
        null=True,
        blank=True,
        verbose_name="秒杀价格"
    )
    stock_count = models.IntegerField(null=True, blank=True, verbose_name="秒杀库存数量")
    start_date = models.DateTimeField(null=True, blank=True, verbose_name="秒杀开始时间")
    end_date = models.DateTimeField(null=True, blank=True, verbose_name="秒杀结束时间")

    class Meta:
        db_table = 'seckill_goods'
        verbose_name = "秒杀商品"
        verbose_name_plural = "秒杀商品列表"

    def __str__(self):
        return f"秒杀商品: {self.goods.goods_name}"

    @property
    def is_active(self):
        """判断秒杀是否正在进行"""
        from django.utils.timezone import now
        current_time = now()
        return self.start_date <= current_time <= self.end_date if self.start_date and self.end_date else False

    @property
    def remain_seconds(self):
        """计算秒杀倒计时剩余秒数"""
        from django.utils.timezone import now
        if not self.start_date:
            return 0
        remaining = (self.start_date - now()).total_seconds()
        return max(int(remaining), 0)